package club.web51.classroom_tool.Controllers;

import club.web51.classroom_tool.DO.collDO.Academy;
import club.web51.classroom_tool.DO.roleDO.Student;
import club.web51.classroom_tool.DO.sysDO.Msg;
import club.web51.classroom_tool.Enums.MsgEnum;
import club.web51.classroom_tool.Exceptions.ErrDataException;
import club.web51.classroom_tool.Services.StudentService;
import club.web51.classroom_tool.Utils.MsgUtil;
import club.web51.classroom_tool.Utils.ObjectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

/**
 * 服务类
 * @author HanYuhao
 * @since 1.0.0
 */
@RestController
@CrossOrigin
@RequestMapping("/student")
@Api(value = "学生模块",tags={"学生操作接口"})
@RequiresPermissions(logical = Logical.AND, value = {"3","2", "1"})
public class StudentController {

    final
    StudentService studentService;

    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }

    /**
     * 根据Student的字段,自动生成条件,字段的值为null不生成条件
     * http://localhost:8080/user/?id=1
     * @param student 实体对象
     * @param pageable 分页/排序对象
     * @return 返回的是实体,里面涵盖分页信息及状态码
     */
     @GetMapping
     @ApiOperation("动态查询，可输入对应对象的一个或多个属性")
     @RequiresPermissions(logical = Logical.OR, value = {"3","2", "1"})
     ResponseEntity<Object> search(Student student, Pageable pageable) {
             return studentService.search(student, pageable);
     }
    @PostMapping
    @ApiOperation("创建学生")
    @RequiresPermissions(logical = Logical.OR, value = {"3","2"})
    Msg create(@RequestBody @Valid Student student, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            throw new ErrDataException(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        student.setId(null);
        studentService.updateOne(student);
        return MsgUtil.success();
    }
    @PutMapping
    @ApiOperation("修改学生")
    @RequiresPermissions(logical = Logical.OR, value = {"3","2"})
    Msg update(Student student){
        if(ObjectUtil.isNull(student.getId()))
            throw new ErrDataException(MsgEnum.ERROR_DATA_EMPTY);
        studentService.updateOne(student);
        return MsgUtil.success();
    }
    @DeleteMapping("/")
    @ApiOperation("删除学生，输入ID")
    @RequiresPermissions(logical = Logical.OR, value = {"3","2"})
    Msg delete(Long id){
        studentService.deleteOne(id);
        return MsgUtil.success();
    }
}
